import datetime
import json
import random
from fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.exceptions import AuthJWTException

from utils.hash import md5
from utils.tools import is_blank, process_error
from fastapi import APIRouter, Header, Depends, HTTPException
from pydantic import BaseModel
from models.requests import UserLogin
from components.db import prisma


from fastapi_jwt_auth.exceptions import MissingTokenError, JWTDecodeError
from utils.resp import BusinessException, resp_err, resp_json, resp_ok, resp_data



logins_router = APIRouter()


# https://github.com/IndominusByte/fastapi-jwt-auth/blob/master/examples/csrf_protection_cookies.py
# https://indominusbyte.github.io/fastapi-jwt-auth/configuration/cookies/

@logins_router.post("/login")
async def user_login(item: UserLogin, Authorize: AuthJWT = Depends()):
    try:
       res = await prisma.user.find_first(
            where={
                "name": item.name,
                "password": md5(item.password),
            }
        )
       
       if res is None:
        return resp_json(-1, "用户名或密码错误")
       else:

        # 生成JWT令牌
        payload = {'user_name': res.name, 'user_id': md5(str(res.id)), 'role': res.role}


        # Create the tokens and passing to set_access_cookies or set_refresh_cookies
        access_token = Authorize.create_access_token(
            subject=json.dumps(payload),
            # subject=res.name,
            expires_time=86400
        )

        refresh_token = Authorize.create_refresh_token(subject=res.name)

        # Set the JWT cookies in the response
        Authorize.set_access_cookies(access_token)
        Authorize.set_refresh_cookies(refresh_token)

        
        return resp_data({"access_token": access_token})
    except Exception as e:
        process_error(e)



@logins_router.delete('/logout')
def logout(Authorize: AuthJWT = Depends()):
    """
        Because the JWT are stored in an httponly cookie now, we cannot
        log the user out by simply deleting the cookie in the frontend.
        We need the backend to send us a response to delete the cookies.
    """
    try:
        Authorize.jwt_required()

        Authorize.unset_jwt_cookies()
        return resp_ok("Successfully logout")
    
    except Exception as e:
        process_error(e)



# protect endpoint with function jwt_required(), which requires
# a valid access token in the request headers to access.
@logins_router.get('/user_info')
async def user_info(Authorize: AuthJWT = Depends()):
   

    try:
        Authorize.jwt_required()

        current_user = Authorize.get_jwt_subject()
        current_user = json.loads(current_user)
        print(current_user)

        return resp_data(current_user)
    except Exception as e:
        process_error(e)
    
   
